/*
 * @(#)RegistryException.java
 * Date 2013-10-05
 * Version 1.0
 * Author Jim Horner
 * Copyright (c)2012
 */


package us.hornerscorners.lamppost.registry.exception;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import oasis.names.tc.ebxml_regrep.xsd.rim._3.IdentifiableType;

import us.hornerscorners.lamppost.exception.ServiceActionError;
import us.hornerscorners.lamppost.exception.ServiceActionException;

import us.hornerscorners.lamppost.model.common.PersistableModelType;


/**
 * Class description
 *
 *
 * @version        v1.0, 2013-10-05
 * @author         Jim Horner
 */
public class RegistryException extends ServiceActionException {

    public RegistryException(IdentifiableType idtype, PersistableModelType type,
                             Class location, ServiceActionError[] errors) {

        super(location, transformErrors(type, idtype, Arrays.asList(errors)));
    }

    /**
     * Constructs ...
     *
     *
     * @param idtype
     * @param location
     * @param errors
     */
    public RegistryException(IdentifiableType idtype, PersistableModelType type,
                             Class location, Collection<ServiceActionError> errors) {

        super(location, transformErrors(type, idtype, errors));
    }

    /**
     * Constructs ...
     *
     *
     * @param location
     * @param error
     */
    public RegistryException(IdentifiableType idtype, PersistableModelType type,
                             Class location, ServiceActionError error) {

        super(location, transformErrors(type, idtype, Collections.singletonList(error)));
    }

    /**
     * Method description
     *
     *
     * @param errors
     *
     * @return
     */
    private static Collection<ServiceActionError> transformErrors(
            PersistableModelType type, IdentifiableType idtype,
            Collection<ServiceActionError> errors) {

        List<ServiceActionError> result = new ArrayList<>();

        for (ServiceActionError error : errors) {

            String msg = String.format("%s [%s] - %s", type.name(), idtype.getId(),
                                       error.getCodeContext());

            result.add(new ServiceActionError(error.getErrorCode(), msg,
                                              error.getSeverity()));
        }

        return result;
    }
}
